package cn.kgc.vue.controller;

import cn.hutool.core.util.IdUtil;
import cn.kgc.vue.anno.LogAnnotation;
import cn.kgc.vue.common.Operation;
import cn.kgc.vue.common.ResponseResult;
import cn.kgc.vue.common.ResponseStatus;
import cn.kgc.vue.entity.Template;
import cn.kgc.vue.service.TemplateService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author: 课工场
 * @since 2023/8/22
 * 资源下载模块
 */
@RestController
@RequestMapping("source")
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @GetMapping("page")
    public ResponseResult getPage(String fileName,Integer limit,Integer currentPage){

        Page<Template> templatePage = new Page<>(currentPage, limit);
        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.like(StringUtils.hasLength(fileName),Template::getFileName,fileName);
        templateService.page(templatePage,lambda);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",templatePage.getTotal());
        map.put("currentPageData",templatePage.getRecords());

        ResponseResult responseResult = new ResponseResult();
        responseResult.success(ResponseStatus.SUCCESS,map);
        return responseResult;

    }

    @GetMapping("download")
    public void downloadSource(HttpServletResponse response,String fileName) throws Exception {

        FileInputStream fileInputStream = new FileInputStream("D:/upload/" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(fileInputStream,outputStream);
        outputStream.close();
        fileInputStream.close();
    }

    @PostMapping("upload")
    @LogAnnotation(model = "资源中心模块",operation = Operation.ADD)
    @RequiresPermissions(value = {"source:file:upload"})
    public ResponseResult uploadSource(@RequestParam("file") MultipartFile file) throws IOException {
        ResponseResult responseResult = new ResponseResult();
        if (file.isEmpty()) {
            responseResult.setMsg("文件为空");
            responseResult.setCode(500);
            return responseResult;
        }

        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename = " + originalFilename);
        String uuid = IdUtil.simpleUUID();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuidName = uuid+"."+filenameExtension;
        long size = file.getSize();

        File f = new File("D:/upload/" + uuidName);
        // 上传文件
        file.transferTo(f);
        HashMap<String, Object> map = new HashMap<>();
        map.put("uuidName", uuidName);
        map.put("size",size/1024);
        responseResult.success(ResponseStatus.SUCCESS,map);
        return responseResult;
    }

    @PostMapping("add")
    @LogAnnotation(model = "资源中心模块",operation = Operation.ADD)
    @RequiresPermissions(value = {"source:file:upload"})
    public ResponseResult addSourceInfo(@RequestBody Template template){

        templateService.save(template);
        ResponseResult responseResult = new ResponseResult();
        responseResult.success();
        return responseResult;
    }

    @DeleteMapping("delete")
    @RequiresRoles("admin")
    public ResponseResult deleteSourceInfo(String uuid){
        // 删除磁盘中文件
        File file = new File("D:/upload/" + uuid);
        file.delete();

        // 删除资源在数据库中的信息
        LambdaQueryWrapper<Template> lambda = new QueryWrapper<Template>().lambda();
        lambda.eq(Template::getUuidName,uuid);
        templateService.remove(lambda);

        ResponseResult responseResult = new ResponseResult();
        responseResult.success();
        return responseResult;
    }

}
